import React, { ReactElement } from 'react';
import { render, RenderOptions } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';

import { theme } from '@/styles/theme';

// 创建测试专用的QueryClient
const createTestQueryClient = () => new QueryClient({
  defaultOptions: {
    queries: {
      retry: false,
      staleTime: Infinity,
    },
  },
});

// 自定义渲染器，包含所有必要的Provider
interface CustomRenderOptions extends Omit<RenderOptions, 'wrapper'> {
  queryClient?: QueryClient;
  initialEntries?: string[];
}

const customRender = (
  ui: ReactElement,
  options: CustomRenderOptions = {}
) => {
  const { 
    queryClient = createTestQueryClient(),
    initialEntries = ['/'],
    ...renderOptions 
  } = options;

  const AllTheProviders = ({ children }: { children: React.ReactNode }) => {
    return (
      <BrowserRouter>
        <QueryClientProvider client={queryClient}>
          <ThemeProvider theme={theme}>
            <CssBaseline />
            {children}
          </ThemeProvider>
        </QueryClientProvider>
      </BrowserRouter>
    );
  };

  return render(ui, { wrapper: AllTheProviders, ...renderOptions });
};

// 创建模拟的认证用户
export const createMockUser = (overrides = {}) => ({
  id: 'test-user-id',
  username: 'testuser',
  email: 'test@example.com',
  profile: {
    fullName: '测试用户',
    phoneNumber: '13800138000',
    avatar: '',
    department: '技术部',
    position: '开发工程师'
  },
  tenants: [{
    id: 'tenant-1',
    name: '测试租户',
    status: 'active' as const,
    subscription: {
      plan: 'enterprise' as const,
      status: 'active' as const,
      expiresAt: '2024-12-31T23:59:59Z'
    }
  }],
  organizations: [{
    id: 'org-1',
    name: '测试组织',
    tenantId: 'tenant-1'
  }],
  roles: [{
    id: 'role-1',
    name: '系统管理员',
    permissions: ['user:read', 'user:write', 'tenant:read', 'tenant:write']
  }],
  permissions: ['user:read', 'user:write', 'tenant:read', 'tenant:write'],
  status: 'active' as const,
  lastLoginAt: new Date().toISOString(),
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString(),
  ...overrides
});

// 创建模拟的租户数据
export const createMockTenant = (overrides = {}) => ({
  id: 'tenant-1',
  name: '测试租户',
  code: 'TEST_TENANT',
  domain: 'test.example.com',
  status: 'active' as const,
  subscription: {
    plan: 'enterprise' as const,
    status: 'active' as const,
    startDate: '2024-01-01T00:00:00Z',
    expiresAt: '2024-12-31T23:59:59Z',
    features: ['multi_org', 'advanced_auth', 'api_access']
  },
  settings: {
    allowSelfRegistration: true,
    requireEmailVerification: true,
    sessionTimeout: 8,
    maxLoginAttempts: 5,
    enableAuditLog: true,
    enableDataExport: true
  },
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString(),
  ...overrides
});

// 创建模拟的组织数据
export const createMockOrganization = (overrides = {}) => ({
  id: 'org-1',
  name: '测试组织',
  code: 'TEST_ORG',
  description: '这是一个测试组织',
  tenantId: 'tenant-1',
  parentId: null,
  level: 1,
  sort: 1,
  status: 'active' as const,
  settings: {
    enableDepartmentTree: true,
    enablePositionManagement: true,
    dataIsolation: 'organization' as const,
    allowCrossDepartmentAccess: false
  },
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString(),
  ...overrides
});

// 等待异步操作完成的辅助函数
export const waitForLoadingToFinish = () => {
  return new Promise(resolve => setTimeout(resolve, 0));
};

// 导出所有测试工具
export * from '@testing-library/react';
export { default as userEvent } from '@testing-library/user-event';
export { customRender as render };